#!/bin/sh

## path env 目录一定要有三级以上(项目\服务\工程)
ABC_PATH=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
CURDIR=$(echo $ABC_PATH |rev | awk -F "/" '{print $1}' | rev)
CURDIR_PARENT=$(echo $ABC_PATH |rev | awk -F "/" '{print $2}' | rev)
CURDIR_PARENT_P=$(echo $ABC_PATH |rev | awk -F "/" '{print $3}' | rev)

echo "=== PATH : $ABC_PATH"
echo "=== CURDIR :  $CURDIR , APP_NAME : $CURDIR"
echo "=== SERVICE : $CURDIR_PARENT , PROJECT : $CURDIR_PARENT_P"

#服务名称
APP_NAME=$CURDIR

#部署路径
SERVICE_DIR=$ABC_PATH
SERVICE_NAME=$CURDIR_PARENT_P-$CURDIR_PARENT-$APP_NAME
JAR_NAME=$APP_NAME*\.jar
PID=$SERVICE_NAME\.pid

cd $SERVICE_DIR

case "$1" in

    start)
        nohup $JRE_HOME/bin/java -Xms128m -Xmx1024m -jar $JAR_NAME >/dev/null 2>&1 &
        echo $! > $SERVICE_DIR/$PID
        echo "=== start $SERVICE_NAME"
        ;;

    stop)
        kill `cat $SERVICE_DIR/$PID`
        rm -rf $SERVICE_DIR/$PID
        echo "=== stop $SERVICE_NAME"

        sleep 5
        P_ID=`ps -ef | grep -w "$SERVICE_NAME" | grep -v "grep" | awk '{print $2}'`
        if [ "$P_ID" == "" ]; then
            echo "=== $SERVICE_NAME process not exists or stop success"
        else
            echo "=== $SERVICE_NAME process pid is:$P_ID"
            echo "=== begin kill $SERVICE_NAME process, pid is:$P_ID"
            kill -9 $P_ID
        fi
        ;;

    restart)
        $0 stop
        sleep 2
        $0 start
        echo "=== restart $SERVICE_NAME"
        ;;

    *)
        ## restart
        $0 stop
        sleep 2
        $0 start
        ;;
esac
exit 0

